使用SpringBoot + Mybatis快速搭建Spring Restful开发环境

最近项目需要用Spring搭建一个Restful API项目,因此重拾了很久没用的JAVA,发现Spring多了一个SpringBoot项目,集成了嵌入式Tomcat,Jetty容器,无需部署WAR包,Mybatis也有类似的与Spring集成的东西,叫 mybatis-spring-boot ,这两个可以免除写一堆XML配置文件,以前写JAVA痛苦的XML配置过程不堪回首,所以干脆用这个搭一个吧。其实官方给的例子已经很详细了,下面是搭建的经验,懂的可以不用看了。

官方链接:

https://spring.io/guides/gs/rest-service/

https://github.com/mybatis/mybatis-spring-boot

  1. 建立Maven项目,我用的是IDEA
  2. 复制pom.xml,添加依赖文件

    <?xml version=”1.0” encoding=”UTF-8”?>
    <project xmlns=”http://maven.apache.org/POM/4.0.0"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
    

    <modelVersion>4.0.0</modelVersion>

    <groupId>visoon</groupId>
    <artifactId>visoon</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>

    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
    &lt;version&gt;1.3.2.RELEASE&lt;/version&gt;
    

    </parent>

    <properties>

    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;java.version&gt;1.8&lt;/java.version&gt;
    

    </properties>

    <dependencies>

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
        &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
        &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;/dependency&gt;
    
    &lt;!--mysql--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt;
        &lt;artifactId&gt;tomcat-jdbc&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;/dependency&gt;
    

    </dependencies>

    <build>

    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
    

    </build>

    <repositories>

    &lt;repository&gt;
        &lt;id&gt;spring-releases&lt;/id&gt;
        &lt;url&gt;https://repo.spring.io/libs-release&lt;/url&gt;
    &lt;/repository&gt;
    

    </repositories>
    <pluginRepositories>

    &lt;pluginRepository&gt;
        &lt;id&gt;spring-releases&lt;/id&gt;
        &lt;url&gt;https://repo.spring.io/libs-release&lt;/url&gt;
    &lt;/pluginRepository&gt;
    

    </pluginRepositories>
    </project>
     

  3. 一般项目结构是这样的:QQ截图20160205210959
  4. 编写Application.java
    package cn.visoon;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan(“cn.visoon.wechat.mapper”)
public class Application {
private static Logger logger = Logger.getLogger(Application.class);

@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
    return new org.apache.tomcat.jdbc.pool.DataSource();
}

@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource());

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));

    return sqlSessionFactoryBean.getObject();
}

@Bean
public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dataSource());
}

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

}

 

  1. 编写User.java
    package cn.visoon.wechat.model;

public class User {
private Integer id;
private String name;
private Integer age;
private String password;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

}

 

  1. 编写UserService.java
    package cn.visoon.wechat.service;

import cn.visoon.wechat.mapper.UserMapper;
import cn.visoon.wechat.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
@Autowired
private UserMapper userMapper;

public User getUserInfo() {
    User user = userMapper.findUserInfo();
    return user;
}

}

 

  1. 编写UserMapper.java
    package cn.visoon.wechat.mapper;

import cn.visoon.wechat.model.User;

public interface UserMapper {
public User findUserInfo();
}

 

  1. 编写UserController.java
    package cn.visoon.wechat.controller;

import cn.visoon.wechat.model.User;
import cn.visoon.wechat.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class UserController {

private Logger logger = Logger.getLogger(UserController.class);

@Autowired
private UserService userService;

@RequestMapping("/getUser")
public User getUser() {
    User user = userService.getUserInfo();
    if (user != null) {
        logger.info("user.getId():" + user.getId());
        logger.info("user.getAge():" + user.getAge());
        logger.info("user.getName():" + user.getName());
    }
    return user;
}

}

 

  1. 配置数据库
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

     
  2. 配置log4j
    #config root logger
    log4j.rootLogger = INFO,system.out
    log4j.appender.system.out=org.apache.log4j.ConsoleAppender
    log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
    log4j.appender.system.out.layout.ConversionPattern=[Log] %5p[%F:%L]:%m%n

#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
log4j.appender.thisProject.file.out.File=logContentFile.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout

 

  1. 配置查询SQL。UserMapper.xml

    <?xml version=”1.0” encoding=”UTF-8”?>
    <!DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN” “http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace=”cn.visoon.wechat.mapper.UserMapper”>

    <select id=”findUserInfo” resultType=”cn.visoon.wechat.model.User”>
    select id, name, age,password from user;
    </select>

</mapper>
 

  1. 最后,运行Application.java,像运行java应用程序一样。程序就跑起来了~